package com.hunttown.common.dao.sharding;

import com.hunttown.common.sharding.client.RouteFactor;
import com.hunttown.common.sharding.client.annotation.ISharding;
import com.hunttown.common.sharding.client.annotation.Sharding;
import com.hunttown.common.sharding.client.router.Router;
import com.hunttown.common.sharding.client.support.RouteResult;
import java.util.Map;
import org.springframework.util.Assert;

public class ShardingUtil {
    public ShardingUtil() {
    }

    public static final String getLogicTableName(Object shardingObj) {
        String logicTableName = null;
        if (shardingObj instanceof Sharding) {
            logicTableName = ((Sharding)shardingObj).getLogicTableName();
        } else if (shardingObj instanceof ISharding) {
            logicTableName = ((ISharding)shardingObj).getLogicTableName();
        } else if (shardingObj instanceof Map) {
            logicTableName = (String)((Map)shardingObj).get("logicTableName");
        }

        Assert.notNull(logicTableName, "sharding object must set logicTableName attribute.");
        return logicTableName;
    }

    public static final RouteResult doRoute(ShardingRouters shardingRouters, Object shardingObj) {
        String logicTableName = getLogicTableName(shardingObj);
        Assert.notNull(logicTableName, "sharding router must not null, logic table name [" + logicTableName + "].");
        Router router = shardingRouters.getRouter(logicTableName);
        Assert.notNull(router, "sharding router must not null, logic table name [" + logicTableName + "].");
        RouteFactor routeFactor = new RouteFactor(logicTableName);
        routeFactor.setParameter(shardingObj);
        RouteResult routeResult = router.doRoute(routeFactor);
        return routeResult;
    }
}